import React from 'react';
import { Card, Button, Table, Space, Modal, message, TableProps } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaEducationalTeachingSrv } from '@/service/teacher';
import {
  COURSE,
  COURSE_CATEGORY,
  OTHER_WORK,
  PART_TIME_JOB,
  SEMESTER,
  SUBJECT_CATEGORY,
  TEACHING_SECTIONS,
} from '@/constant/teachOptions';
import { isPermissionOperate } from '@/component/permission-button';

const TeacherEdu: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const columns: TableProps['columns'] = [
    {
      title: '学年',
      dataIndex: 'academic_year',
      key: 'academic_year',
    },
    {
      title: '学期',
      dataIndex: 'semester',
      key: 'semester',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(SEMESTER, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '任教教学段',
      dataIndex: 'teaching_stage',
      key: 'teaching_stage',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(TEACHING_SECTIONS, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '任课课程类别',
      dataIndex: 'course_category',
      key: 'course_category',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(COURSE_CATEGORY, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '任课学科类别',
      dataIndex: 'subject_category',
      key: 'subject_category',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(SUBJECT_CATEGORY, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '任课课程',
      dataIndex: 'course_name',
      key: 'course_name',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(COURSE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '平均每周课堂教学课时数',
      dataIndex: 'average_weekly_teaching_hours',
      key: 'average_weekly_teaching_hours',
    },
    {
      title: '承担其他工作',
      dataIndex: 'other_responsibilities',
      key: 'other_responsibilities',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(OTHER_WORK, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '平均每周其他工作折合教学课时数',
      dataIndex: 'average_weekly_other_duties_hours',
      key: 'average_weekly_other_duties_hours',
    },
    {
      title: '兼任工作',
      dataIndex: 'concurrent_job',
      key: 'concurrent_job',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(PART_TIME_JOB, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '兼任其他工作名称',
      dataIndex: 'concurrent_job_name',
      key: 'concurrent_job_name',
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '学年',
          name: 'academic_year',
          key: 'academic_year',
          required: true,
          inputType: InputType.select,
          renderOption: () => {
            const years = [];
            for (let i = 0; i < 10; i++) {
              years.push({
                value: `${new Date().getFullYear() - i}`,
                label: `${new Date().getFullYear() - i}`,
              });
            }
            return years;
          },
        },
        {
          label: '学期',
          name: 'semester',
          key: 'semester',
          required: true,
          inputType: InputType.select,
          span: 12,
          renderOption: SEMESTER,
        },
        {
          label: '任教学段',
          name: 'teaching_stage',
          key: 'teaching_stage',
          required: true,
          inputType: InputType.select,
          renderOption: TEACHING_SECTIONS,
        },
        {
          label: '任课课程类别',
          name: 'course_category',
          key: 'course_category',
          required: true,
          inputType: InputType.select,
          renderOption: COURSE_CATEGORY,
        },
        {
          label: '任课学科类别',
          name: 'subject_category',
          key: 'subject_category',
          required: true,
          inputType: InputType.select,
          renderOption: SUBJECT_CATEGORY,
        },
        {
          label: '任课课程',
          name: 'course_name',
          key: 'course_name',
          required: true,
          inputType: InputType.select,
          renderOption: COURSE,
        },
        {
          label: '平均每堂课堂教学课堂数',
          name: 'average_weekly_teaching_hours',
          key: 'average_weekly_teaching_hours',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '承担其他工作',
          name: 'other_responsibilities',
          key: 'other_responsibilities',
          inputType: InputType.select,
          renderOption: OTHER_WORK,
        },
        {
          label: '平均每周其他工作折合教学课时数',
          name: 'average_weekly_other_duties_hours',
          key: 'average_weekly_other_duties_hours',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '兼任工作',
          name: 'concurrent_job',
          key: 'concurrent_job',
          required: true,
          inputType: InputType.select,
          renderOption: PART_TIME_JOB,
        },
        {
          label: '兼任工作名称',
          name: 'concurrent_job_name',
          key: 'concurrent_job_name',
          required: false,
          textRange: [0, 20],
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();

  const [formValue, setFormValue] = React.useState({});
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaEducationalTeachingSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };

  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaEducationalTeachingSrv.detail(record.educational_teaching_id);

    const params = {
      ...data,
      academic_year: data.academic_year ? data.academic_year?.split(',') : [],
      semester: data.semester ? data.semester?.split(',') : [],
      teaching_stage: data.teaching_stage ? data.teaching_stage?.split(',') : [],
      course_category: data.course_category ? data.course_category?.split(',') : [],
      subject_category: data.subject_category ? data.subject_category?.split(',') : [],
      course_name: data.course_name ? data.course_name?.split(',') : [],
      other_responsibilities: data.other_responsibilities ? data.other_responsibilities?.split(',') : [],
      concurrent_job: data.concurrent_job ? data.concurrent_job?.split(',') : [],
    };

    setCurrentRowId(record.educational_teaching_id);
    setFormValue(params);

    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除学年: ${record.academic_year} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaEducationalTeachingSrv.delete(record.educational_teaching_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
    };

    //params.academic_year = params.academic_year?.join(',');
    //params.semester = params.semester?.join(',');
    //params.teaching_stage = params.teaching_stage?.join(',');
    //params.course_category = params.course_category?.join(',');
    //params.subject_category = params.subject_category?.join(',');
    //params.course_name = params.course_name?.join(',');
    //params.other_responsibilities = params.other_responsibilities?.join(',');
    //params.concurrent_job = params.concurrent_job?.join(',');

    if (isEdit) {
      params.educational_teaching_id = currentRowId;
    }

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaEducationalTeachingSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="教育教学" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '教育教学编辑' : '教育教学详情') : '教育教学新增'}
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

TeacherEdu.defaultProps = {
  isEditPanel: true,
};

export default TeacherEdu;
